package com.qiniuyun.graph.common.service.impl;

import com.qiniuyun.graph.common.config.service.RedisCacheConfiguration;
import com.qiniuyun.graph.common.dao.UsersDao;
import com.qiniuyun.graph.common.entity.Users;
import com.qiniuyun.graph.common.enums.ErrorCodeEnum;
import com.qiniuyun.graph.common.exception.ServiceException;
import com.qiniuyun.graph.common.service.CacheService;
import com.qiniuyun.graph.common.service.UserService;
import com.qiniuyun.graph.common.utils.DateUtil;
import com.qiniuyun.graph.common.utils.SecuritySHA1Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private RedisCacheConfiguration cacheConfiguration;

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Override
    public Map<String, String> getTokenByIp(String ipAddr, String signature) {
        Users users = usersDao.queryUserByIp(ipAddr);
        if (users == null) {
            throw new ServiceException(ErrorCodeEnum.E001.code(), ErrorCodeEnum.E001.getDescription());
        }
        try {
            String checkSign = this.generateSignature(ipAddr, users.getPassword());
            if (!checkSign.equals(signature)) {
                throw new ServiceException(ErrorCodeEnum.E003.code(), ErrorCodeEnum.E003.getDescription());
            }
            Map<String, String> map = new HashMap();
            map.put("api_key", this.generateApiKey());

            return map;
        } catch (Exception e) {
            logger.info("||===getTokenByIp===|| error msg: {}", e.getMessage());
            throw new ServiceException(ErrorCodeEnum.E002.code(), e.getMessage());
        }
    }

    @Override
    public String generateSignature(String ipAddr, String salt) throws Exception {
        //获取当天的开始时间
        String unixDate = String.valueOf(DateUtil.startOfTodDay());
        //按照time+ip+salt拼接字符串
        StringBuilder sb = new StringBuilder();
        sb.append(ipAddr);
        sb.append(salt);
        sb.append(unixDate);
        String str = sb.toString();
        //返回sha1加密的签名
        return SecuritySHA1Utils.shaEncode(str);
    }

    @Override
    public String generateApiKey() {
        //生成api key并记录redis
        String apiKey = UUID.randomUUID().toString();
        cacheService.put(apiKey, apiKey, cacheConfiguration.getApiKeyTimeOut());
        return apiKey;
    }
}
